<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
</head>
<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <div>
            <input type="file" name="file" id="file" onchange="javascript:setPersPhotoPreview();"/>
        </div>
        <button type="submit">上传</button>
    </form>
    <div>
        <img id="show_img">
    </div>
</body>
<script th:inline="javascript">
    /*<![CDATA[*/
    function setPersPhotoPreview() {
        var docObj=document.getElementById("file");
        // var valid = $(docObj).valid();
        // var docObjButton=document.getElementById("personPhotoButton");
        // valid = valid && $(docObjButton).valid();
        // //验证不通过，不进行预览
        // if(!valid){
        //     return;
        // }
        var imgObjPreview=document.getElementById("show_img");
        if(docObj.files && docObj.files[0]) {
            var fileTypeArr = docObj.value.split('.');
            var fileType = fileTypeArr[fileTypeArr.length - 1];
            if (fileType != null) {
                fileType = fileType.toLowerCase();
                if (fileType == 'jpg' || fileType == 'jpeg' || fileType == 'gif' || fileType == 'png' || fileType == 'bmp') {
                    //火狐下，直接设img属性
                    imgObjPreview.style.display = 'block';
                    imgObjPreview.style.width = '120px';
                    imgObjPreview.style.height = '140px';
                    //imgObjPreview.src = docObj.files[0].getAsDataURL();
                    //火狐7以上版本不能用上面的getAsDataURL()方式获取，需要一下方式
                    imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
                }
            }
        } else {
            //IE下，使用滤镜
            docObj.select();
            var imgSrc = document.selection.createRange().text;
            var localImagId = document.getElementById("localImag");
            //必须设置初始大小
            localImagId.style.width = "120px";
            localImagId.style.height = "140px";
            //图片异常的捕捉，防止用户修改后缀来伪造图片
            try {
                localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
            } catch (e) {
                openMessage(msgType.error, I18n.getValue("pers_person_msg3"));
                return false;
            }
            imgObjPreview.style.display = 'none';
            document.selection.empty();
        }
        return true;
    }
    /*]]>*/
</script>
</html>